package m2;

import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer {
    public static void main(String[] args)  throws IOException, TimeoutException {
        ConnectionFactory f = new ConnectionFactory();
        f.setHost("wht6.cn"); // 192.168.64.140
        f.setPort(5672);
        f.setUsername("admin");
        f.setPassword("admin");
        Channel c = f.newConnection().createChannel();
        /*
        服务器端已经存在的队列，属性不允许修改，
         */
        c.queueDeclare("task_queue-tyhgbevdwe", true,false,false,null);

        // 回调对象
        DeliverCallback deliverCallback = (consumerTag, message) -> {
            String s = new String(message.getBody());
            System.out.println("收到："+s);
            // 处理消息，遍历字符串，遇到.字符就暂停1秒，来模拟耗时消息
            for (int i = 0; i < s.length(); i++) {
                if ('.' == s.charAt(i)) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                    }
                }
            }

            // 手动发送回执
            // c.basicAck(回执, 是否同时确认之前收到的所有消息);
            c.basicAck(message.getEnvelope().getDeliveryTag(), false);
            System.out.println("------------------消息处理完成");
        };
        CancelCallback cancelCallback = consumerTag -> {};

        // 每次只接收1条，处理完之前，不收下一条
        // 手动ack模式下才有效
        c.basicQos(1);

        // 消费消息
        /*
         第二个参数 autoAck
            true    - 自动确认
            false   - 手动确认
         */
        c.basicConsume("task_queue-tyhgbevdwe", false, deliverCallback, cancelCallback);
    }
}
